from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
import os
import time
import json

from django.urls import reverse
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from app.models import User, Goods, C_f
from app.serializers import FriendSerializer
from app.utils import to_md5_hex


def register(request):
    """注册"""
    if request.method == 'GET':
        return render(request, 'register.html')
    if request.method == 'POST':
        name = request.POST.get('username')
        pw = request.POST.get('password')
        user = User.objects.filter(username=name)
        if not user:
            password = to_md5_hex(pw)
            User.objects.create(username=name, password=password)
            return render(request, 'login.html')
        return render(request, 'register.html')

def indexshow(request):
    """首页"""
    return render(request, 'index.html')


def login(request):
    """登录"""
    if request.method == 'GET':
        return render(request, 'login.html')
    if request.method == 'POST':
        name = request.POST.get('username')
        pw = request.POST.get('password')
        user = User.objects.filter(username=name).first()
        if user:
            password = to_md5_hex(pw)
            if user.password == password:
                request.session['user_id'] = user.no
                return HttpResponseRedirect('/app/index/')
        return render(request, 'login.html')


def edit(request):
    """富文本编辑"""
    if request.method == 'GET':
        return render(request, 'edit.html')
    if request.method == 'POST':
        name = request.POST.get('username')
        pw = request.POST.get('password')
        user = User.objects.filter(username=name)
        if not user:
            password = to_md5_hex(pw)
            User.objects.create(username=name, password=password)
            return render(request, 'login.html')
        return render(request, 'register.html')


def yinchang(request):
    """隐藏自己发布的内容"""
    id = request.session['user_id']
    res = User.objects.filter(no=id).first()
    for i in res.pengyou.all():
        i.yinchang = 1
        i.save()
    return HttpResponse('ok')


def upload_img(request):
    """上传图片"""
    if request.method == 'POST':
        request.GET.get('dir')
        img = (request.FILES.get('fafafa'))
        category = Goods()
        category.c_image = img
        category.save()
        image = C_f()
        image.image_name = img.name
        image.user_id_id = request.session['user_id']
        image.save()
        print('img:',img)
        # 获取文件保存
        # import json
        dic = {                             #后台向前端返回的值
            'error': 0,                    #0表示的是正确的,1代表错误
            'url': f'/media/goods/images/{img}',
            'message': 'OK...'
        }

        return HttpResponse(json.dumps(dic))


def my_f(request):
    """自己的发布内容"""
    if request.method == 'GET':
        return render(request, 'my_f.html')
    if request.method == 'POST':
        id = request.session['user_id']
        my_lists = C_f.objects.filter(user_id_id=id).all()
        list = []
        for li in my_lists:
            list.append(li.image_name)
        result = {'results':list}
        return HttpResponse(json.dumps(result), content_type="application/json")


def file_manager(request):
    """上传文件"""
    dic = {}
    root_path = 'D:/week/static'
    static_root_path = '/static/'
    request_path = request.GET.get('path')
    if request_path:
        abs_current_dir_path = os.path.join(root_path, request_path)
        move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
        dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path

    else:
        abs_current_dir_path = root_path
        dic['moveup_dir_path'] = ''     #  上一级目录

    dic['current_dir_path'] = request_path  #current_dir_path 指当前的路径
    dic['current_url'] = os.path.join(static_root_path, request_path)

    file_list = []            #文件目录
    for item in os.listdir(abs_current_dir_path):         #listdir 就是把某一路径下的东西全部拿下来
        abs_item_path = os.path.join(abs_current_dir_path, item)
        a, exts = os.path.splitext(item)
        is_dir = os.path.isdir(abs_item_path)
        if is_dir:
            temp = {
                'is_dir': True,   #是否是dir
                'has_file': True, #目录下面是否存在文件
                'filesize': 0,   #文件大小是多少
                'dir_path': '',  #当前的路径是在哪
                'is_photo': False,  #是否是图片
                'filetype': '',    #文件的类型是什么
                'filename': item,  #文件名是什么
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path))) #文件创始时间是什么
            }
        else:
            temp = {
                'is_dir': False,
                'has_file': False,
                'filesize': os.stat(abs_item_path).st_size,
                'dir_path': '',
                'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
                'filetype': exts.lower().strip('.'),
                'filename': item,
                'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
            }

        file_list.append(temp)
    dic['file_list'] = file_list
    return HttpResponse(json.dumps(dic))


class CustomPagination(PageNumberPagination):
    """自定义分页"""
    page_size = 2
    page_size_query_param = 'size'
    max_page_size = 50


class FriendsSiendet(viewsets.ModelViewSet):
    """朋友圈首页内容分页"""
    #指定结果集并设置排序
    # user_xian = User.objects.filter(yinchang=0)
    queryset = C_f.objects.filter(yinchang=0).order_by('-fdate')

    # #指定序列化的类
    serializer_class = FriendSerializer
    pagination_class = CustomPagination

    # return Response(serilizer.data)

